package com.haitonghop.modules.local;


import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Hashtable;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haitonghop.R;
import com.haitonghop.controls.IOnComicChanged;
import com.haitonghop.controls.ImagePagerAdapter;
import com.haitonghop.controls.ViewPagerSupportImageView;
import com.haitonghop.data.HaiBLMetalData;
import com.haitonghop.main.ComicBussiness;
import com.haitonghop.main.DisplayUtils;
import com.haitonghop.utils.Logger;

public class LocalViewComicActivity extends Activity implements IOnComicChanged{

	private ImagePagerAdapter imageComicAdapter;
	private int mainIdTopic = -1;
	private String nameTitle = "Truyện đã lưu";
	private ArrayList<HaiBLMetalData> comicLists;
	private TextView imageDescription;
	private ViewPagerSupportImageView viewPager;
	private LinearLayout menuBar;
	private LinearLayout loadingError;
	private TextView errorMessage;
	private CheckBox maskToDeleted;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		//Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.offline_activity_layout);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			mainIdTopic = extras.getInt("ID");
			nameTitle  = extras.getString("NAME");
		    Logger.logMe("value = "+mainIdTopic);
		}
		init();

		maskToDeleted = (CheckBox)findViewById(R.id.maskToDeleted);
		maskToDeleted.setVisibility(View.VISIBLE);
		maskToDeleted.setOnClickListener(clickListenerDeletedMask);
		TextView textView = (TextView)findViewById(R.id.titleActivity);
		textView.setText(nameTitle);

		Button deletedButton = (Button)findViewById(R.id.btnMoreFunctions);
		deletedButton.setVisibility(View.GONE);


		//Button more -> Button deleted
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					onBackActivity();
				}
			});
		}
	}

	void afterDeletedDone(){
//		runOnUiThread(new Runnable() {
//			public void run() {
//
//				final int afterSize = comicLists.size() - 1;
//				if(afterSize <= 0){
//					DisplayUtils.openNoticeDialog("Thông báo", "Không còn truyện nào trong chủ đ�? này nữa.", LocalViewComicActivity.this, new DialogInterface.OnClickListener() {
//
//						public void onClick(DialogInterface dialog, int which) {
//							finish();
//						}
//					});
//				} else {
//
//					int currentIndex = imageAdapter.getCurrentViewIndex();
//					comicLists.remove(currentIndex);
//					viewPager.setCurrentItem(0, true);
//					viewPager.setOffscreenPageLimit(0);
//					viewPager.invalidate();
//
//					imageAdapter.setNewData(comicLists);
//					imageAdapter.notifyDataSetChanged();
//
//					viewPager.setOffscreenPageLimit(1);
//					viewPager.invalidate();
//				}
//			}
//		});
	}

	public static boolean isEnterFirst = true;
	Hashtable<String, HaiBLMetalData> hashMaskDeleted = new Hashtable<String, HaiBLMetalData>();
	OnClickListener clickListenerDeletedMask = new OnClickListener() {

		@Override
		public void onClick(View v) {

			final HaiBLMetalData blMetalData = imageComicAdapter.getCurrentData();
			if(blMetalData != null){

				if(isEnterFirst){
					isEnterFirst = false;
					DisplayUtils.openNoticeDialog("Xóa truyện", "Truyện sẽ được đánh dấu và xóa ngay sau khi bạn đóng màn hình này, bạn có thể hủy b�? thao tác này" +
							" bằng cách hủy dấu check ở nút Xóa đi.", LocalViewComicActivity.this, null);
				}

				String id = blMetalData.getId();
				if(!hashMaskDeleted.containsKey(id)){
					hashMaskDeleted.put(id, blMetalData);
					maskToDeleted.setChecked(true);
				} else {
					hashMaskDeleted.remove(id);
					maskToDeleted.setChecked(false);
				}
			}

		}
	};

	void onBackActivity() {
		int size = hashMaskDeleted.size();
		if (size > 0) {
			DisplayUtils.openConfirmDialog("Xóa truyện", "Bạn đang đánh dấu xóa " + size + " truyện. Bạn thật sự muốn xóa (những) truyện này đi?", LocalViewComicActivity.this, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {

					ArrayList<HaiBLMetalData> datas = new ArrayList<HaiBLMetalData>();
					Enumeration<HaiBLMetalData> dataset =  hashMaskDeleted.elements();
					while(dataset.hasMoreElements()){
						datas.add(dataset.nextElement());
					}
					hashMaskDeleted.clear();
					ComicBussiness.getInstance(LocalViewComicActivity.this).deletedComic(datas);

					finish();
				}
			}, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			});
		} else {
			finish();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			onBackActivity();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		if(imageComicAdapter != null){
			imageComicAdapter.clearListener();
		}
		super.onDestroy();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		onStartUp();
	}

	private int lastId = -1;
	long currentRequestId = -1;

	void init() {
	}

	@Override
	public void commicChanged(HaiBLMetalData blMetalData) {
		if (blMetalData != null && imageDescription != null ) {
			imageDescription.setText(blMetalData.getTitleDescription());
		}
		if(blMetalData != null){
			String id = blMetalData.getId();
			if(hashMaskDeleted.containsKey(id)){
				maskToDeleted.setChecked(true);
			} else {
				maskToDeleted.setChecked(false);
			}
		}
	}

	public void onStartUp() {
		viewPager = (ViewPagerSupportImageView) findViewById(R.id.view_pager);

		final LinearLayout loading = (LinearLayout) findViewById(R.id.loadingpage);
		loadingError = (LinearLayout) findViewById(R.id.loadingError);
		imageDescription = (TextView)findViewById(R.id.imageDescription);
		menuBar = (LinearLayout)findViewById(R.id.menubar);
		errorMessage  = (TextView)findViewById(R.id.errorMessageView);

		loadingError.setVisibility(View.GONE);
		viewPager.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);
		menuBar.setVisibility(View.INVISIBLE);

		imageComicAdapter = new ImagePagerAdapter(this);
		imageComicAdapter.setComicChanged(this);
		viewPager.setOnPageChangeListener(imageComicAdapter);

		comicLists = ComicBussiness.getInstance(LocalViewComicActivity.this).getComicFromDataBase(mainIdTopic);
		if(comicLists != null){
			imageComicAdapter.setMetalData(comicLists);
		}
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				loading.setVisibility(View.GONE);
				if(comicLists == null || (comicLists != null && comicLists.isEmpty())){
					loadingError.setVisibility(View.VISIBLE);
					errorMessage.setText("Bạn chưa lưu truyện nào.");
				} else {
					menuBar.setVisibility(View.VISIBLE);
					viewPager.setVisibility(View.VISIBLE);
					viewPager.setAdapter(imageComicAdapter);
					imageComicAdapter.onPageSelected(0);
					viewPager.invalidate();
				}
			}
		});
	}
}
